<template>
  <eui-background type="common">
    <eui-nav-bar ref="BcmNavBar" title="缺货登记" />
    <view class="footer" :style="{ height: height + 'px' }" v-if="goodsList.length > 0">
      <view
        style="width: 100%; background: #FFE9DA;padding: 15rpx 20rpx 15rpx 15rpx;color:#FF0000;box-sizing: border-box;font-size: 32rpx;line-height: 35rpx;"
        class="flex just-between align-center">
        <view style="flex: 1;">提示：缺货登记成功后，系统会将商品库存调整为0同步到各渠道</view>
      </view>
      <view
        style="height: 68rpx;font-size: 32rpx;line-height: 35rpx;padding: 17rpx 17rpx 10rpx 10rpx;box-sizing: border-box;"
        class="flex align-center just-between">
        <view style="flex: 1;">请选择缺货登记的商品</view>
      </view>
      <scroll-view scroll-y="true" class="bg-white"
        style="width: 100%;padding: 10rpx 18rpx;box-sizing: border-box;overflow-y: scroll;">
        <view class="goods-item" v-for="(item, index) in goodsList" :key="index">
          <checkbox-group @change="checkboxChange(index)">
            <checkbox :value="item.orderGoodsId" :checked="item.checked" />
          </checkbox-group>
          <view
            style="width: 41rpx;height: 41rpx;text-align: center;line-height: 41rpx;background-color: #D8D8D8;color: #fff;border-radius: 41rpx;font-size: 32rpx;margin-top: 13rpx;flex-shrink: 0;">
            {{ index + 1 }}
          </view>
          <view style="margin-left: 17rpx;box-sizing: border-box;flex: 1">
            <view>
              <view class="flex just-between align-center">
                <view class="goods-name bold" style="flex: 1;">{{ item.goodsName }}</view>
                <view style="font-weight: bold;text-align: center;" class="icon-stockout goods-quantity"
                  v-if="item.stockoutStatus == '1'">缺货</view>
              </view>
              <view class="flex just-between align-center">
                <view
                  style="font-size: 32rpx;color: #626262;flex: 1;text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">
                  {{ item.goodsCode }}-{{ item.goodsBarcode }}
                </view>
                <view class="goods-quantity"
                  style="color: #FBA433;text-overflow: ellipsis;white-space: nowrap;overflow: hidden;width: 200rpx;">
                  {{ (!(item.stockoutRecoveryMethod == '1')) ? (item.stockoutStatus == '1') ?
      (!!item.stockoutRecoveryTime ? item.stockoutRecoveryTime + ':00' : '暂不恢复') : '' : '库存增加时恢复' }}
                </view>
              </view>
            </view>
            <view style="margin-top: 6rpx;height: 48rpx;font-size: 32rpx;margin-bottom: 10rpx;">
              <view class="flex align-center co-00" style="height: 48rpx;">
                <view>库存</view>
                <view style="margin-left: 15rpx;"><text style="color: #626262;margin-right: 5rpx;">线下</text>{{
      (!!item.offlineStock || item.offlineStock ==
        0) ? item.offlineStock : '-' }}</view>
                <view style="margin-left: 15rpx;"><text style="color: #626262;margin-right: 5rpx;">中台</text>
                  {{ (!!item.stock || item.stock == 0) ? item.stock : '-' }}</view>
                <view style="margin-left: 15rpx;"><text style="color: #626262;margin-right: 5rpx;">预留</text>
                  {{ (!!item.reservedStock || item.reservedStock == 0) ? item.reservedStock : '-' }}</view>
                <view style="margin-left: 15rpx;"><text style="color: #626262;margin-right: 5rpx;">在途</text>
                  {{ (!!item.standByStock || item.standByStock == 0) ? item.standByStock : '-' }}</view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="footer align-center" :style="{ height: height + 'px' }" v-else>
      <view class="m-list-template-image" style="flex: 1;margin-top: 25%;">
        <image :src="_img_blank_order" />
        <view style="color: #9e9e9e;font-size: 32rpx;text-align: center;">无可缺货登记的商品</view>
      </view>
    </view>
    <eui-button v-if="goodsList.length > 0" title="确认登记" type="min" singleTag="confirm"
      style="width: 100%;height: 86rpx;line-height: 86rpx;margin: 0;border-radius: 0;padding: 0;font-size: 28rpx;"
      @buttonClick="buttonClick"></eui-button>
    <eui-popup ref="popup" background-color="#fff" type="bottom" :mask-click="false">
      <view class="popup-content">
        <view class="popup-title flex just-between">
          <view style="font-weight: bold;">
            选择恢复时间
          </view>
          <bcm-close-btn @click="close"></bcm-close-btn>
        </view>
        <view style="box-sizing: border-box;height: 70vh;overflow-y: scroll;text-align: left;">
          <view
            style="padding:10rpx 22rpx;line-height: 40rpx;background-color: #DFF3FF;color: #5AA2FC;font-size: 28rpx;margin-bottom: 15rpx;">
            提示：已是“缺货”状态的商品再次登记缺货，以最后一次为准</view>
          <view style="padding-left: 40rpx;">
            <view class="flex" style="align-items: baseline;">
              <view>恢复方式：</view>
              <view>
                <radio-group @change="selectRecoveryMethodItem">
                  <view v-for="(item, index) in getBcmDictList('stockoutRecoveryMethod')" :key="index"
                    style="margin-bottom: 20rpx;width: 100%;text-align: left">
                    <radio :value="item.value" :checked="recoveryMethod === item.value" style="width: 100%;">
                      {{ item.text }}
                    </radio>
                  </view>
                </radio-group>
              </view>
            </view>
            <view v-if="recoveryMethod == '0'" class="flex" style="align-items: baseline;">
              <view>恢复时间：</view>
              <radio-group @change="selectItem">
                <view v-for="(item, index) in configList" :key="index" style="margin-bottom: 20rpx;width: 100%;">
                  <radio :value="index" :checked="timeType === index" style="width: 100%;">
                    {{ item.desc }}
                    <eui-datetime-picker type="datetime" @change="changeTime" :border="true" v-if="item.type == '4'"
                      :hide-second="true" placeholder="请选择恢复时间" style="margin-left: 40rpx;" :start="start" />
                  </radio>
                </view>
              </radio-group>
            </view>
          </view>
        </view>
        <view class="bottom-1">
          <eui-button type="primary" title="确认" style="width: 50%;" singleTag="sure" @buttonClick="buttonClick" />
        </view>
      </view>
    </eui-popup>
  </eui-background>
</template>
<script setup>
import { mapState, mapMutations } from 'vuex';
import { ref, computed, onMounted } from 'vue';
import dayjs from 'dayjs';
import { onLoad } from "@dcloudio/uni-app";
import service from '../../../common/service';
import { bcmRequest, getBcmUrl } from '../../../hooks/bcmServices';
import { getBcmDictList } from '../../../hooks/bcmUseUntils';
import _img_blank_order from '../../../static/img/status/blank_order.png'
import BcmCloseBtn from '../components/BcmCloseBtn.vue';

const bcmUrl = getBcmUrl()

const goodsList = ref([])
const timeType = ref(0)
const recoveryTime = ref(null)
const configList = ref([])
const height = ref(0)
const recoveryMethod = ref('0')
const start = ref(dayjs().format('YYYY-MM-DD HH:mm'))
const popup = ref(null)

onMounted(() => {
  uni.getSystemInfo({
    success: function (res) { // res - 各种参数
      let info = uni.createSelectorQuery().select(".navigation");
      info.boundingClientRect(function (data) { //data - 各种参数
        // height.value = res.windowHeight - data.height - 100;
      }).exec()
    }
  });
})

const selectItem = function (e) {
  timeType.value = e.detail.value;
}

const selectRecoveryMethodItem = function (e) {
  recoveryMethod.value = e.detail.value;
}

const changeTime = function (e) {
  recoveryTime.value = e;
}

const checkboxChange = function (index) {
  let list = [...goodsList.value]
  const item = list[index];
  item.checked = !item.checked;
  // $set(item, 'checked', !item.checked)
  goodsList.value = list;
}

const buttonClick = async function (t) {
  const { singleTag } = t;
  let list = goodsList.value.filter(a => !!a.checked);
  switch (singleTag) {
    case 'sure':
      let stockoutTimeItem;
      if (recoveryMethod.value == '0') {
        stockoutTimeItem = configList.value?.find((v, i) => i == timeType.value);
        if (stockoutTimeItem?.type == '4') {
          if (!!recoveryTime) {
            stockoutTimeItem.time = recoveryTime.value;
          } else {
            uni.showToast({
              title: '请填写【自定义】恢复时间',
              icon: 'none'
            });
            return false
          }
        }
      }

      let params = {
        stockoutStatus: '1',
        idList: list.map(v => {
          return v.storeGoodsStockId
        }),
        stockoutRecoveryMethod: recoveryMethod.value,
        stockoutTimeItem
      }
      service.enjoyShowLoading('正在处理...');
      const response = await bcmRequest(bcmUrl.stockApi, '门店商品库存表', 'UpdateGoodsStockout', params);
      service.enjoyHideLoading();
      if (response.Flag == '1') {
        popup.value.close('bottom');
        uni.showToast({
          title: '处理成功',
          icon: 'none',
        });
        setTimeout(() => {
          uni.navigateBack({
            delta: 1
          });
          uni.$emit('REFRESH_ORDER_SEARCH_LIST')
          uni.$emit('REFRESH_ORDER_SEARCH_DATA')
          uni.$emit('REFRESH_ORDER_DETAIL_DATA')
        }, 1000)
      } else {
        uni.showToast({
          title: response.Msg,
          icon: 'none',
          duration: 500,
        });
      }
      break;
    case 'confirm':
      if (list.length == 0) {
        uni.showToast({
          title: '请选择需要登记的商品',
          icon: 'none'
        });
        return;
      }
      popup.value.open('bottom');
      break;
  }
}

const close = function () {
  popup.value.close();

}

const handleGetStockoutGoodsList = async function (param) {
  // service.enjoyShowLoading('正在加载...');
  const response = await bcmRequest(bcmUrl.stockApi, '门店商品库存表',
    'BatchQueryStoreGoodsStock', param);
  // service.enjoyHideLoading();
  goodsList.value = response;
}

const handleGetStockoutConfig = async function () {
  const ObjectData = {
    IsNotPage: true,
    extras: {
      isQueryDefault: true
    },
    WhereList: [{
      c_col: 'paramName',
      c_oper: '等于',
      c_value: 'STOCKOUT_RECOVER_TIME_ITEM',
    }]
  }
  const response = await bcmRequest(bcmUrl.managerApi, '配置表',
    'EnjoyQueryList', ObjectData);
  let config = JSON.parse(response.ReturnObject[0]?.paramValue);

  let time = config.find(v => v.type == '4')?.time;
  if (!!time) {
    recoveryTime.value = time
  }
  configList.value = config?.sort((a, b) => a.type - b.type)
}

onLoad(() => {
  let options = service.getStorageSync('orderItemStockout');
  let list = [];
  options.goodsList?.map(v => {
    list.push({
      goodsBarcode: v.goodsBarcode,
      goodsCode: v.goodsCode
    })
  })
  handleGetStockoutGoodsList({
    storeCode: options.storeCode,
    goodsList: list
  });
  handleGetStockoutConfig();
})

</script>
<style lang="scss" scoped>
@import "@/static/font/enjoyicon/iconfont.css";
@import "../common/common.css";

uni-checkbox {
  ::v-deep .uni-checkbox-input {
    transform: scale(.6);
  }
}

.footer {
  display: flex;
  flex-direction: column;
  flex: 1;
  background: #f5f7fa;
}

.bottom {
  display: flow-root;
  height: 76rpx;
  text-align: center;
}

::v-deep .uni-date-x {
  width: 330rpx;
  height: 50rpx;
  color: #626262;
  font-size: 32rpx;
}

.bottom-1 {
  display: flex;
  justify-content: center;
  flex: 0 0 auto;
  height: 70rpx;
  padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
  background: $uni-bg-color;
}

//list
.goods-item {
  display: flex;
  justify-content: space-between;
  padding: 10rpx 0;
  border-bottom: 1rpx solid #e1e1e1;
}

.goods-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.m-list-template-image {
  width: 100%;
  margin: auto 0;
  text-align: center;
}

.goods-name {
  margin-bottom: 2px;
  font-size: 32rpx;
  line-height: 35rpx;
}

.goods-price {
  font-size: 32rpx;
  text-align: right;
}

.goods-quantity {
  font-size: 32rpx;
}

.icon-stockout {
  width: 80rpx;
  height: 36rpx;
  color: #fff;
  line-height: 36rpx;
  background-color: #fba433;
  border-radius: 15rpx;
}

.popup-content {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 0;
  background-color: #fff;

  .popup-title {
    display: flex;
    align-items: center;
    box-sizing: border-box;
    width: 100%;
    height: 100rpx;
    padding-right: 36rpx;
    padding-left: 30rpx;
    font-size: 33rpx;
    line-height: 100rpx;
    border-bottom: 1px solid #f1f1f1;
  }

  textarea {
    box-sizing: border-box;
    width: 100%;
    height: 80px;
    padding: 5px;
    margin: 5px 0;
    border: 1px solid #ccc;
    border-radius: 5px;
  }
}
</style>
